package com.github.data_manage.controller

import com.github.data_manage.dao.FundDao
import com.github.data_manage.domain.po.User
import com.github.data_manage.service.FundDeepResearchService
import com.github.data_manage.service.FundDepthResearchAttachService
import com.github.data_manage.service.SpiderService
import com.github.data_manage.util.AuthContextHolder
import io.swagger.v3.oas.annotations.tags.Tag
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.bind.annotation.GetMapping
import org.springframework.web.bind.annotation.RequestMapping
import org.springframework.web.bind.annotation.RequestParam
import org.springframework.web.bind.annotation.RestController


@RestController
@RequestMapping("/tests")
@Tag(name = "TestController", description = "仅用于测试,无实际意义")
class TestController(
    private val spiderService: SpiderService
) {

    companion object{

        private val logger = LoggerFactory.getLogger(this::class.java)

    }

    @Autowired
    private lateinit var authContextHolder: AuthContextHolder

    @Autowired
    lateinit var fundDao: FundDao

    @Autowired
    lateinit var fundDeepResearchService: FundDeepResearchService

    @Autowired
    lateinit var fundDepthResearchAttachService: FundDepthResearchAttachService

    @GetMapping("calcFundDeepResearch")
    fun calcFundDeepResearch(@RequestParam fundId: Int) {
        Thread.startVirtualThread {
            logger.info("开始计算")
            fundDepthResearchAttachService.handleAttachInfo(fundDao.findById(fundId).orElseThrow())
            fundDepthResearchAttachService.handleContrastAttach(fundDao.findById(fundId).orElseThrow())
            logger.info("计算完成")
        }
    }

    @GetMapping("calcAllFundDeepResearch")
    fun calcAllFundDeepResearch() {
        Thread.startVirtualThread {
            logger.info("开始计算基金信息")
            fundDao.findAll().forEach { fund ->
                logger.info("开始计算基金{}深度调研信息", fund.fundName)
//                val fundDepthResearch =
//                    fundDeepResearchService.findByFundId(fund.fundId!!) ?: FundDepthResearch(fund.fundId!!)
//                try {
//                    fundDeepResearchService.handleDepthResearchInfo(fund, fundDepthResearch)
//                } catch (e: Exception) {
//                    logger.error("计算基金[{}]的深度调研信息发生错误", fund.fundId!!, e)
//                }
                logger.info("开始计算基金{}深度调研附加信息", fund.fundName)
                fundDepthResearchAttachService.handleAttachInfo(fund)
                logger.info("开始计算基金{}深度调研附加指数对比信息", fund.fundName)
                fundDepthResearchAttachService.handleContrastAttach(fund)

            }
            logger.info("完成计算基金信息")
        }
    }


    @GetMapping("/contrastSpider")
    fun contrastSpider() {
        spiderService.contrastMonthValueSpider()
    }

    @GetMapping("/currentUser")
    fun currentUser(): User {
       return authContextHolder.currentUser()
    }

}